<script setup lang='ts' name="ManagePhysicalKnowlege">
import {ref, reactive, onMounted, watch, computed, onActivated} from 'vue'
import {FormRules, ElMessage} from 'element-plus'
import {FromItem} from '@/components/dFrom/dFrom'
import dFrom from '@/components/dFrom/dFrom.vue'
import {PositiveInteger, transfDicArrData} from '@/util/common'
import {routerPush} from '@/util/router'
import {
  KnowlegeRuleItem,
  KnowlegeRuleItemGroup,
  KnowlegeData,
  getKnowlegeData,
  saveKnowlegeData,
  getCategoryList,
  getItemGroupList,
  getItemList
} from '@/api/physicalExaminationManager/physicalKnowlege'



import {SeleteData, IconConfig, ColorRed, ColorTheme} from '@/api/config'

import dIcon from '@/components/dIcon.vue'

import pageContainer from '@/components/pageContainer.vue'

import {textTypeOption} from './textTypeOption'
import addGuide from './addGuide.vue'

import {useRoute} from 'vue-router'
import useStore from '@/store/common'
import useNav from '@/store/nav'
const nav = useNav.setup().store
const route = useRoute()
const {store} = useStore.setup()

const loading = ref(false)

const rules = reactive<FormRules>({
  healthJudgment: [
    {message: '长度应不超过200个字符', trigger: ['change', 'blur'], max: 200}
  ],
  advise:[
    {message: '长度应不超过2000个字符', trigger: ['change', 'blur'], max: 2000}
  ],
  modules:[
    {required:true, message: '请填写判断规则', trigger: ['change', 'blur']}
  ],
  ageRangeLow:[
    {message: '长度应不超过10个字符', trigger: ['change', 'blur'], max: 10},
    {message: '请输入正整数', pattern:PositiveInteger, trigger: ['change', 'blur']}
  ],
  ageRangeHigh:[
    {message: '长度应不超过10个字符', trigger: ['change', 'blur'], max: 10},
    {message: '请输入正整数', pattern:PositiveInteger, trigger: ['change', 'blur']}
  ],
  rangeMinInput:[
    {message: '长度应不超过50个字符', trigger: ['change', 'blur'], max: 50}
  ],
  rangeMaxInput:[
    {message: '长度应不超过50个字符', trigger: ['change', 'blur'], max: 50}
  ],
  vaccines_info:[
    {message: '长度应不超过100个字符', trigger: ['change', 'blur'], max: 100}
  ],
  other_info:[
    {message: '长度应不超过100个字符', trigger: ['change', 'blur'], max: 100}
  ]
})

// 危险因素控制初始数据
const dangerousControlObjInit = {
  selected:[],
  vaccines_info:'',
  other_info:''
}

//判断规则-最小规则初始数据
const knowlegeRuleItemInit:KnowlegeRuleItem = {
  id:undefined,
  ruleJudgeId:	undefined,	//判断规则id
  inspectCategoryId:undefined, //体检大类id
  itemGroupId:undefined, //项目组合编码
  itemGroupList:[],
  itemId:undefined, //项目id
  itemList:[],
  itemObj:null,
  target:'',	//指标（存json）
  targetObj:{selected:''},
  targetType:1,
  gender:undefined, //性别(字典)
  ageRangeLow:undefined, //年龄下限值
  ageRangeHigh:undefined //年龄上限值
}
//判断规则-最小规则组初始数据
const knowlegeRuleItemGroupInit:KnowlegeRuleItemGroup = {
  id:null,
  ruleId:null, //知识库规则id
  type:null, // 判断规则且0或1（忽略第一条）
  sort:null, //排序
  details:[]
}

//表单数据
const formDataBase = {
  id:'',
  name:'',
  groupingName:'',
  isException:false,
  modules:[],
  healthJudgment:'',
  advise:'',
  healthGuide:'',
  healthGuideArr:[],
  guideDisplayValue:'',
  guideCheckboxValue:'',
  dangerousControlObj:{...dangerousControlObjInit},
  dangerousControl:''
}
const formData = ref<KnowlegeData>({
  ...formDataBase
})

//表单项
const fromItems = reactive<Array<FromItem>>([
  {label: '判断规则', prop: 'modules',   type:'slot', slotName:'modules'   },
  {label: '健康评价', prop: 'healthJudgment', type: 'input', inputType: 'textarea'},
  {label: '建议', prop: 'advise', type: 'input', inputType: 'textarea'},
  {label: '健康指导', prop: 'healthGuide', type:'slot', slotName:'healthGuide' },
  {label: '健教指导内容', prop: 'guideDisplayValue', type: 'slot', slotName: 'guideDisplayValue', class:{'guide-display-value':true}},
  {label: '危险因素控制', prop: 'dangerousControl', type:'slot', slotName:'dangerousControl' }
])
const healthList = [
  {text:'纳入慢性患者健康管理', label:'1'},
  {text:'建议复查', label:'2'},
  {text:'建议转诊', label:'3'}
]
const dangerousList = [
  {text:'戒烟', label:'1'},
  {text:'限酒', label:'2'},
  {text:'合理饮食', label:'3'},
  {text:'适当锻炼', label:'4'},
  {text:'减体重', label:'5'},
  {text:'建议接种疫苗', label:'6'},
  {type:'input', name:'vaccines_info'},
  {text:'其他', label:'7'},
  {type:'input', name:'other_info'}
]

//表单清除控制
const resetFieldsFlag = ref(false)

const validateFlag = ref(false)

//表单验证通过事件
const onSubmit = () => {
  const submitData = JSON.parse(JSON.stringify(formData.value))
  submitData.healthGuide = submitData.healthGuideArr.join(',')
  submitData.dangerousControl = JSON.stringify(submitData.dangerousControlObj)
  submitData.modules = submitData.modules.filter(moduleItem => {
    moduleItem.details = moduleItem.details.filter(ruleItem => {
      if (ruleItem.inspectCategoryId && ruleItem.itemGroupId && ruleItem.itemId) {
        ruleItem.target = JSON.stringify(ruleItem.targetObj),
        ruleItem.itemGroupList = [],
        ruleItem.itemList = []
        return true
      }
    })
    if (moduleItem.details.length > 0) {
      return true
    }
  })
  if (!submitData.modules.length) {
    ElMessage.error('请填写至少一个规则')
    return
  }
  // console.log(submitData)
  // return
  saveKnowlegeData(submitData).then((res) => {
    res.data.msg && ElMessage.success(res.data.msg)
    routerPush('PhysicalKnowlege')
    nav.closeTab('ManagePhysicalKnowlege')
  })
}
// 保存按钮
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}
// 取消按钮
const onCancel = () => {
  routerPush('PhysicalKnowlege')
  nav.closeTab('ManagePhysicalKnowlege')
}

const addIconConfig = <IconConfig>{icon:'common-addItem', type:'custom', size:20, color: ColorTheme}
const deleteIconConfig = <IconConfig>{icon:'common-delete', type:'custom', size:20, color: ColorRed}
const relationIconConfig =  <IconConfig>{icon:'common-change', type:'custom', size:12, color:'#fff'}

const currKnowlegeId = ref()
//获取知识库详情数据
const getFormData = () => {
  formData.value = {...formDataBase}
  getKnowlegeData(currKnowlegeId.value).then(res => {
    const {data} = res.data

    if (data.modules.length < 3) {
      const modulesData = <Array <KnowlegeRuleItemGroup>> []
      //根据排序，插入缺少的module（3个module，每个module中至少一条规则）
      for (let i = 0; i < 3; i++) {
        let pushTag = false
        data.modules.forEach(item => {
          if (i === item.sort) {
            modulesData.push(item)
            pushTag = true
          }
        })
        if (!pushTag) {
          modulesData.push({
            ...knowlegeRuleItemGroupInit,
            details:[{...knowlegeRuleItemInit}],
            type:i === 2 ? 1 : 0, //第三个module的关系默认为或，第一第二个默认为且
            sort:i,
            ruleId:currKnowlegeId.value
          })
        }
      }
      data.modules = modulesData
    }

    data.healthGuideArr = data.healthGuide ? data.healthGuide.split(',') : []
    data.dangerousControlObj = data.dangerousControl ? JSON.parse(data.dangerousControl) : {...dangerousControlObjInit}
    data.modules.forEach(moduleItem => {
      moduleItem.details.forEach(ruleItem => {
        if (ruleItem.target) {
          ruleItem.targetObj = JSON.parse(ruleItem.target)
        }
        ruleItem.ageRangeLow = (typeof ruleItem.ageRangeLow !== 'undefined' && ruleItem.ageRangeLow !== null) ?  ruleItem.ageRangeLow + '' : ''
        ruleItem.ageRangeHigh = (typeof ruleItem.ageRangeHigh !== 'undefined' && ruleItem.ageRangeHigh !== null) ? ruleItem.ageRangeHigh + '' : ''
      })
    })
    formData.value = data
  })
}

//修改module之间的关系
const changeRelation = (item) => {
  if (item.type === 0) {
    item.type = 1
  } else {
    item.type = 0
  }
}

//增加最小规则
const addRuleItem = (ruleModule, index) => {
  const newItem = {...knowlegeRuleItemInit}
  newItem.ruleJudgeId = ruleModule.id ?? null
  ruleModule.details.splice(index + 1, 0, {...knowlegeRuleItemInit})
}
//减少最小规则
const deleteRuleItem = (ruleModule, index) => {
  ruleModule.details.splice(index, 1)
}

//范围型指标选项
const targetRangeOption = [ '=', '>', '≥', '<', '≤', '不包含', '包含']
//选项型指标选项
const selectTypeOption = [{label:'正常', value:'1'}, {label:'异常', value:'2'}]

//性别选项
const genderList = ref<Array<SeleteData>>([])
//单位选项
const unitList = ref<Array<SeleteData>>([])
//获取字典
const getDic = () => {
  store.getDicData('gender_apply').then((res) => {
    genderList.value = transfDicArrData(res)
  })
  store.getDicData('unit').then((res) => {
    unitList.value = transfDicArrData(res)
  })
}

// 体检大类选项
const categoryList = ref<Array<SeleteData>>([])
const getCategoryData = () => {
  getCategoryList().then((res) => {
    const {data} = res.data
    categoryList.value = data.map(category => {
      return {
        label:category.categoryName,
        value:category.id
      }
    })
  })
}

//显示弹窗
const showDialog = ref(false)

//关闭窗口事件
const onClose = () => {
  showDialog.value = false
  // searchData()
}

//获取项目详细信息及初始化指标值
const getItemInfo = (ruleItem, moduleIndex, ruleIndex) => {
  const currItem = formData.value.modules[moduleIndex].details[ruleIndex]?.itemList?.find(item => {
    return item.id === ruleItem.itemId
  })

  if (currItem) {
    if (currItem?.checkType === 3 || (currItem?.checkType === 1 && currItem?.resultType === 2)) {
      formData.value.modules[moduleIndex].details[ruleIndex].targetType = 1 //选项型（检查类型，功能检查文字型）
      if (!ruleItem.target) {
        formData.value.modules[moduleIndex].details[ruleIndex].targetObj = {selected:''}
      }

      formData.value.modules[moduleIndex].details[ruleIndex].target = ''
    } else if (currItem?.checkType === 2 || (currItem?.checkType === 1 && currItem?.resultType === 1)) {
      formData.value.modules[moduleIndex].details[ruleIndex].targetType = 2 //范围型(检验类型，功能检查数值型)
      if (!ruleItem.target) {
        formData.value.modules[moduleIndex].details[ruleIndex].targetObj = {
          rangeMinSelect:'',
          rangeMaxSelect:'',
          rangeMinInput:'',
          rangeMaxInput:''
        }
      }
      formData.value.modules[moduleIndex].details[ruleIndex].target = ''
    }
    formData.value.modules[moduleIndex].details[ruleIndex].itemObj = currItem
  }
}

//formData.value.modules副本，watch此副本的改变，才能获取到oldvalue
const modulesObj = computed(() => {
  return JSON.parse(JSON.stringify(formData.value.modules))
})

watch(
  modulesObj,
  (newValue, oldValue) => {
    newValue.forEach((moduleItem, moduleIndex) => {
      moduleItem.details.forEach((ruleItem, ruleIndex) => {
        // 根据体检大类查询项目组合列表
        if (ruleItem.inspectCategoryId !== oldValue?.[moduleIndex]?.details?.[ruleIndex]?.inspectCategoryId) {
          if (ruleItem.inspectCategoryId) {
            getItemGroupList(ruleItem.inspectCategoryId).then((res) => {
              const {data} = res.data
              const newData = data.map(item => {
                return {
                  label:item.itemGroupName,
                  value:item.id
                }
              })
              formData.value.modules[moduleIndex].details[ruleIndex].itemGroupList = newData

              const currItemGroupId = formData.value.modules[moduleIndex].details[ruleIndex]?.itemGroupId + ''
              if (!data.map(item => item.id).includes(currItemGroupId)) {
                formData.value.modules[moduleIndex].details[ruleIndex].itemGroupId = undefined
              }
            })
          } else {
            formData.value.modules[moduleIndex].details[ruleIndex].itemGroupList = []
            formData.value.modules[moduleIndex].details[ruleIndex].itemGroupId = undefined
          }
        }
        //根据项目组合查询项目列表及获取项目完整信息
        if (ruleItem.itemGroupId !== oldValue?.[moduleIndex]?.details?.[ruleIndex]?.itemGroupId) {
          if (ruleItem.itemGroupId) {
            getItemList({itemGroupId:ruleItem.itemGroupId}).then((res) => {
              const {data} = res.data
              formData.value.modules[moduleIndex].details[ruleIndex].itemList = data || []

              const currItemId = formData.value.modules[moduleIndex].details[ruleIndex]?.itemId + ''
              if (data.map(item => item.id).includes(currItemId)) {
                getItemInfo(ruleItem, moduleIndex, ruleIndex)
              } else {
                formData.value.modules[moduleIndex].details[ruleIndex].itemId = undefined
              }
            })
          } else {
            formData.value.modules[moduleIndex].details[ruleIndex].itemList = []
            formData.value.modules[moduleIndex].details[ruleIndex].itemId = undefined
          }
        }
        // 项目改变时获取所选项目完整信息
        if (ruleItem.itemId !== oldValue?.[moduleIndex]?.details?.[ruleIndex]?.itemId) {
          if (ruleItem.itemId) {
            getItemInfo(ruleItem, moduleIndex, ruleIndex)
          } else {
            formData.value.modules[moduleIndex].details[ruleIndex].targetType = 1
            formData.value.modules[moduleIndex].details[ruleIndex].targetObj = {selected:''}
          }
        }
      })
    })
  }, {
    deep:true,
    immediate:true
  }
)

//未被选中时，清空后面的input框内容
watch(
  () => formData.value.dangerousControlObj,
  (newValue) => {
    if (!newValue.selected.includes('6')) {
      formData.value.dangerousControlObj.vaccines_info = ''
    }
    if (!newValue.selected.includes('7')) {
      formData.value.dangerousControlObj.other_info = ''
    }
  },
  {
    deep:true
  }
)

watch(
  () => route.query,
  () => {
    const id = route.query?.id
    if (!id) return
    currKnowlegeId.value = id
  }
)

// 生命周期
onMounted(() => {
  const id = route.query?.id
  if (!id) return
  currKnowlegeId.value = id
})

onActivated(() => {
  getDic()
  getCategoryData()
  getFormData()
})

const updateGuideCheckboxValue = (data) => {
  formData.value.guideCheckboxValue = data
}
const updateGuideDisplayValue = (data) => {
  formData.value.guideDisplayValue = data
}


</script>

<template>
  <page-container>
    <div class="title-box">
      <span>规则名称：<em>{{ formData.name }}</em></span> <span>组别：<em>{{ formData.groupingName }}</em></span> <span>纳入异常统计：<em>{{ formData.isException?'是':"否" }}</em></span>
    </div>
    <d-from
      label-position="right"
      :label-width="120"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :rules="rules"
      :form-data="formData"
      :form-items="fromItems"
      :form-line-num="1"
      @submit="onSubmit"
    >
      <template #modules>
        <div class="rules-wrapper">
          <div v-for="ruleModule,ruleModuleindex in formData.modules" :key="ruleModuleindex" class="items-box">
            <div v-if="ruleModuleindex!==0" class="item-relation">
              <el-button type="primary" size="large" @click="changeRelation(ruleModule)">
                {{ ruleModule.type===0?'且':'或' }} <d-icon :icon-config="relationIconConfig" style="margin:1px 0 0 4px" />
              </el-button>
            </div>
            <div v-for="ruleItem,ruleIndex in ruleModule.details" :key="ruleIndex" class="item-box">
              <el-select v-model="ruleItem.inspectCategoryId" placeholder="体检大类" clearable>
                <el-option
                  v-for="item in categoryList"
                  :key="''+item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select v-model="ruleItem.itemGroupId" placeholder="项目组合">
                <el-option
                  v-for="item in ruleItem.itemGroupList"
                  :key="''+item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select v-model="ruleItem.itemId" placeholder="体检项目" filterable>
                <el-option
                  v-for="item in ruleItem.itemList"
                  :key="''+item.id"
                  :label="item.itemName"
                  :value="item.id"
                />
              </el-select>

              <div class="target">
                <!-- 指标值 -->
                <template v-if="ruleItem?.targetType===1">
                  <!-- 选项型（检查类型，功能检查文字型） -->
                  <el-select v-model="ruleItem.targetObj.selected" placeholder="指标值">
                    <template v-if="ruleItem.itemObj?.checkType===3">
                      <el-option
                        v-for="item in selectTypeOption"
                        :key="''+item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </template>
                    <template v-else-if="ruleItem.itemObj">
                      <el-option
                        v-for="item in textTypeOption[ruleItem.itemObj.id]"
                        :key="''+item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </template>
                  </el-select>
                </template>

                <template v-else-if="ruleItem?.targetType===2">
                  <!-- 范围型(检验类型，功能检查数值型)  -->
                  <el-select v-model="ruleItem.targetObj.rangeMinSelect" placeholder="" class="short">
                    <el-option
                      v-for="item in targetRangeOption"
                      :key="item"
                      :value="item"
                      :label="item"
                    />
                  </el-select>
                  <el-form-item :prop="`modules[${ruleModuleindex}].details[${ruleIndex}].targetObj.rangeMinInput`" :rules="rules['rangeMinInput']">
                    <el-input v-model="ruleItem.targetObj.rangeMinInput" placeholder="指标值" />
                  </el-form-item>
                  <el-select v-model="ruleItem.targetObj.rangeMaxSelect" placeholder="" class="short">
                    <el-option
                      v-for="item in targetRangeOption"
                      :key="item"
                      :value="item"
                      :label="item"
                    />
                  </el-select>
                  <el-form-item :prop="`modules[${ruleModuleindex}].details[${ruleIndex}].targetObj.rangeMaxInput`" :rules="rules['rangeMaxInput']">
                    <el-input v-model="ruleItem.targetObj.rangeMaxInput" placeholder="指标值" />
                  </el-form-item>
                  <el-select v-if="ruleItem.itemObj" v-model="ruleItem.itemObj.unit" placeholder="单位" disabled class="short">
                    <el-option
                      v-for="item in unitList"
                      :key="''+item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </div>

              <el-form-item :prop="`modules[${ruleModuleindex}].details[${ruleIndex}].ageRangeLow`" :rules="rules['ageRangeLow']">
                <el-input v-model="ruleItem.ageRangeLow" class="short" placeholder="最小年龄" />
              </el-form-item>
              ~
              <el-form-item :prop="`modules[${ruleModuleindex}].details[${ruleIndex}].ageRangeHigh`" :rules="rules['ageRangeHigh']">
                <el-input v-model="ruleItem.ageRangeHigh" class="short" placeholder="最大年龄" />
              </el-form-item>

              <el-select v-model="ruleItem.gender" placeholder="性别" class="short">
                <el-option
                  v-for="item in genderList"
                  :key="''+item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <div class="item-oper">
                <d-icon v-if="ruleModule.details.length < 4 && ruleIndex===ruleModule.details.length-1" :icon-config="addIconConfig" style="float:left" @click="addRuleItem(ruleModule,ruleIndex)" />
                <d-icon v-if="ruleModule.details.length > 1" :icon-config="deleteIconConfig" style="float:right" @click="deleteRuleItem(ruleModule,ruleIndex)" />
              </div>
            </div>
          </div>
        </div>
      </template>

      <template #healthGuide>
        <el-checkbox-group v-model="formData.healthGuideArr">
          <el-checkbox v-for="item in healthList" :key="item.label" :label="item.label">
            {{ item.text }}
          </el-checkbox>
        </el-checkbox-group>
      </template>

      <template #guideDisplayValue>
        <el-input v-model="formData.guideDisplayValue" :readonly="true" type="textarea" :autosize="{ minRows:2 }" @click="showDialog=true" />
      </template>


      <template #dangerousControl>
        <el-checkbox-group v-model="formData.dangerousControlObj.selected" class="dangerous-checkboxs">
          <template v-for="item in dangerousList" :key="item.label">
            <template v-if="item.type==='input'">
              <el-form-item :prop="`dangerousControlObj.${item.name}`" :rules="rules[item.name]">
                <el-input
                  v-if="(formData.dangerousControlObj.selected.indexOf('6')>-1 && item.name==='vaccines_info') || (formData.dangerousControlObj.selected.indexOf('7')>-1 && item.name==='other_info')"
                  v-model="formData.dangerousControlObj[item.name]"
                  class="checkbox-input"
                />
              </el-form-item>
            </template>

            <el-checkbox v-else :label="item.label">
              {{ item.text }}
            </el-checkbox>
          </template>
        </el-checkbox-group>
      </template>
    </d-from>
    <div class="oper-box">
      <el-button
        v-blur
        class="from-submit-btn"
        :loading="loading"
        @click="onCancel"
      >
        取消
      </el-button>
      <el-button
        v-blur
        type="primary"
        class="from-submit-btn"
        :loading="loading"
        @click="onConfirm"
      >
        保存
      </el-button>
    </div>
    <add-guide
      v-if="showDialog"
      :show-dialog="showDialog"
      :data="formData.guideCheckboxValue"
      @close="onClose"
      @update-guide-checkbox-value="updateGuideCheckboxValue"
      @update-guide-display-value="updateGuideDisplayValue"
    />
  </page-container>
</template>

<style scoped lang="less">
.dangerous-checkboxs{
  display: flex;
}
.title-box{
  height: 40px;
  line-height: 40px;
  background: #F2F2F2;
  padding: 0 30px;
  margin-bottom: 35px;
  display: flex;
  span{
    width: 33.33%;
  }
  em{
    font-weight: bold;
    font-style: normal;
  }
}
.rules-wrapper{
  border-left: 4px solid rgba(28,147,153,0.18);
  padding-left: 30px;
  width: 100%;
}
.items-box{
  border-radius: 4px;
  background: #F2F2F2;
  padding: 9px 10px;
  width: 100%;
  position: relative;

  &+.items-box{
    margin-top: 16px;
  }
  .item-relation{
    position: absolute;
    left: -54px;
    top: -28px;
    .el-button{
      min-width: auto;
      width: 43px;
    }
  }
}
.item-box{
  display: flex;
  align-items: center;
  &+.item-box{
    margin-top: 16px;
  }
  .item-oper{
    width: 45px;
    margin-left:10px;
    flex-shrink: 0;
    // display: flex;
    // justify-content: space-between;
  }

  .target{
    width:30%;
    min-width: 300px;
    flex-shrink: 0;
    display: flex;
    .el-select.short{
      width:70px;
      flex-shrink: 0;
    }
  }
.short{
    width: 100px;
    flex-shrink: 0;
  }
}
.oper-box{
  text-align: center;
  margin-top: 50px;
  // max-width:1500px
}
.el-checkbox{
  margin-right:40px
}
.checkbox-input{
  width: 150px;
  margin-right: 20px;
}
:deep(.guide-display-value .el-form-item__label){
  color: var(--theme-color);
}
</style>
